package com.lengyu.iottransfer.gateway.udp;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class UdpServer {
    private final static Logger logger = LoggerFactory.getLogger(UdpServer.class);

    /**
     * 启动服务
     */

    @Async
    public void bind(int port) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            //UDP方式使用Bootstrap
            Bootstrap serverBootstrap = new Bootstrap();
            serverBootstrap = serverBootstrap.group(eventLoopGroup);
            serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, true)
                                                .option(ChannelOption.SO_RCVBUF, 1024 * 1024) // 缓冲区
                                                .option(ChannelOption.SO_SNDBUF, 1024 * 1024);
            //不需要太多其他的东西，直接这样就可以用
            serverBootstrap = serverBootstrap.handler(new UdpServerHandlerForLcd());
            logger.info("netty udp start! " +  port);
            ChannelFuture f = serverBootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO: handle exception
            logger.error("error",e);
        } finally {
            logger.info("netty udp close!");
            eventLoopGroup.shutdownGracefully();
        }
    }

    /**
     * 启动服务 中仪水表协议解析
     */

    @Async
    public void bindForZhongYiShuiBiao(int port) {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            //UDP方式使用Bootstrap
            Bootstrap serverBootstrap = new Bootstrap();
            serverBootstrap = serverBootstrap.group(eventLoopGroup);
            serverBootstrap = serverBootstrap.channel(NioDatagramChannel.class);
            serverBootstrap = serverBootstrap.option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024) // 缓冲区
                    .option(ChannelOption.SO_SNDBUF, 1024 * 1024);
            //不需要太多其他的东西，直接这样就可以用
            serverBootstrap = serverBootstrap.handler(new UdpServerHandlerForZhongYi());
            logger.info("netty udp start! " +  port);
            ChannelFuture f = serverBootstrap.bind(port).sync();
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            // TODO: handle exception
            logger.error("error",e);
        } finally {
            logger.info("netty udp close!");
            eventLoopGroup.shutdownGracefully();
        }
    }
}
